import json
from datetime import datetime
from json import JSONDecoder

import psycopg2
from flask import g
from .db import get_db


def pull_one_task(node_ID):
    cur = get_db()
    cur.execute("SELECT * FROM drawing_task_queue WHERE node_id=%s AND status='handling'",(node_ID,))
    if len(cur.fetchall()) != 0:
        return None, None
    cur.execute("SELECT task_ID, task_info FROM drawing_task_queue WHERE status='in queue' ")
    mata = cur.fetchone()
    if mata is not None:
        task_ID, task = mata
        cur.execute("UPDATE drawing_task_queue SET node_ID=%s, status='handling', starting_time=%s WHERE task_ID=%s",
                    (node_ID, datetime.now(), task_ID))
        return task, task_ID
    else:
        return None, None

    # return {
    #     'type':'text2img',
    #     'prompt':'ancient castle',
    #     'width': 512,
    #     'height':512,
    #     'sampler': 'Euler a',
    #     'sampling steps': 20,
    # }
